package com.ks.phone.view;

import android.Manifest;
import android.animation.Animator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;

import com.ks.basictools.ActivityManager;
import com.ks.basictools.BaseActivity;
import com.ks.basictools.utils.ToastUtils;
import com.ks.phone.R;
import com.ks.phone.UserManager;
import com.ks.phone.constant.Constants;
import com.ks.phone.databinding.ActivityMainBinding;
import com.ks.phone.manager.CallPhoneManager;
import com.ks.phone.manager.PreferenceManager;
import com.ks.phone.provider.ContextGlobal;
import com.ks.phone.responseBean.UserInfoResponse;
import com.ks.phone.responseBean.UserResponse;
import com.ks.phone.wedget.PopupSetting;
import com.permissionx.guolindev.PermissionX;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends BaseActivity {
    private final String TAG = MainActivity.class.getSimpleName();

    private ActivityMainBinding mBinding;
    private Context context;
    public final ObservableField<String> username = new ObservableField<>();
    public final ObservableField<String> newNum = new ObservableField<>();
    public final ObservableField<String> allocationNum = new ObservableField<>();
    public final ObservableField<String> affiliate = new ObservableField<>();
    private long exitTime = 0L; // 再按一次退出应用
    private PopupSetting popupSetting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mBinding.setActivity(this);
        context = this;
    }

    @Override
    protected void onResume() {
        super.onResume();
        PermissionX.init(this)
                .permissions(Manifest.permission.CALL_PHONE)
                .explainReasonBeforeRequest()
                .onExplainRequestReason((scope, deniedList) -> scope.showRequestReasonDialog(deniedList, "即将申请的权限是程序必须依赖的权限", "知道了"))
                .onForwardToSettings((scope, deniedList) -> scope.showForwardToSettingsDialog(deniedList, "您需要去应用程序设置当中去手动开启权限", "知道了"))
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        CallPhoneManager.getInstance().startTimer();
                    }
                });

        UserResponse.UserDTO user = UserManager.getInstance().getUser();
        Log.d("zhxk", "User = " + user);
        initView(user);
    }

    private void initView(UserResponse.UserDTO user) {
        Map<String, Object> param = new HashMap<>();
        param.put("userid", user.getId());
        param.put("token", PreferenceManager.getInstance().getToken(context));
        XHttp.post(Constants.URL_HOME)
                .params(param)
                .execute(new SimpleCallBack<UserInfoResponse>() {
                    @Override
                    public void onSuccess(UserInfoResponse info) {
                        Log.d("zhxk", "onSuccess: info = " + info);
                        if (info != null) {
                            String aff = PreferenceManager.getInstance().getAffiliate(MainActivity.this);
                            affiliate.set(aff + "   " + info.getUser().getBumen());

                            newNum.set("新数据：" + info.getUser().getNewNum() + "条");
                            allocationNum.set("每日分配" + info.getUser().getAllocationNum() + "条   今日已分配"
                                    + info.getUser().getNowNum() + "条");
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                        Log.e("zhxk", "onError: e = " + e.getMessage());
                        ToastUtils.show(context, e.getMessage());
                    }
                });
        username.set(user.getUsername());

        mBinding.lottieView.setImageAssetsFolder("");
        mBinding.lottieView.setAnimation("data.json");
        mBinding.lottieView.playAnimation();
        mBinding.lottieView.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                Log.e(TAG, "onAnimationStart: ");
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                Log.e(TAG, "onAnimationEnd: ");
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                Log.e(TAG, "onAnimationCancel: ");
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                Log.e(TAG, "onAnimationRepeat: ");
            }
        });
    }

    public void onClick_logout(View ignoreV) {
        XHttp.post(Constants.URL_LOGOUT)
                .params("token", PreferenceManager.getInstance().getToken(this))
                .params("userid", UserManager.getInstance().getUser().getId())
                .execute(new SimpleCallBack<Object>() {
                    @Override
                    public void onSuccess(Object response) throws Throwable {
                        PreferenceManager.getInstance().setToken(MainActivity.this, "");
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        ActivityManager.getInstance().finishActivity(MainActivity.class);
                    }

                    @Override
                    public void onError(ApiException e) {

                    }
                });
    }

    public void onClick_list(View ignoreV) {
        startActivity(new Intent(this, CustomerActivity.class));
    }

    public void onClick_setting(View ignoreV) {
        if (popupSetting == null) {
            popupSetting = new PopupSetting(this);
            popupSetting.setOnConfirmClickListener(v -> {
                String content = popupSetting.getContent();
                String replace = content.replace("/内置SD卡", Environment
                        .getExternalStorageDirectory().getAbsolutePath());
                PreferenceManager.getInstance().setRecordPath(ContextGlobal.get().getContext(), replace);
                popupSetting.dismiss();
                ToastUtils.show(ContextGlobal.get().getContext(), "保存成功");
            });
        }
        if (!popupSetting.isShowing()) {
            popupSetting.showPopupWindow();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在Activity销毁时取消任务的执行
        CallPhoneManager.getInstance().stopTimer();
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            exitTime = System.currentTimeMillis();
            ToastUtils.show(this, "再按一次退出应用");
        } else if ((System.currentTimeMillis() - exitTime) >= 100) {
            ActivityManager.getInstance().AppExit(ContextGlobal.get().getApplicationContext());
            super.onBackPressed();
        }
    }
}